import mx.utils.Delegate;

import org.molamil.acto.core.EventConstants;
import org.molamil.acto.mc.mcw.LcMcWrapper;

/**
 * XXX: Comment.
 * 
 * @author Jorge Hernandez
 */
class org.molamil.acto.mc.McwChain {
	
	
	// Properties
	
	private var mcwQeue:Array;	private var currentMcw:LcMcWrapper;
	
	private var mcStateChangeDelegate:Function;
	
	
	// Constructor
	
	public function McwChain() {
		mcwQeue = new Array();
		mcStateChangeDelegate = Delegate.create(this, mcStateChangeListener);
	}
	
	
	// Functions
	
	public function add(mcw:LcMcWrapper, isClearBuffer:Boolean):Void {
		mcw.addEventListener(EventConstants.MC_STATE_CHANGE, mcStateChangeDelegate);
		var prev:LcMcWrapper = mcwQeue[mcwQeue.length - 1];
		if (isClearBuffer && mcwQeue.length > 1)
			mcwQeue = mcwQeue.splice(1);
		mcwQeue.push(mcw);
		if (prev == null) {
			mcw.state = LcMcWrapper.STATE_IN;
			currentMcw = mcw;
		} else {
			var current:LcMcWrapper = mcwQeue[0];
			current.state = LcMcWrapper.STATE_OUT;
		}
	}
	
	public function remove(mcw:LcMcWrapper):Void {
		if (mcw == currentMcw) {
			mcw.state = LcMcWrapper.STATE_OUT;
		} else {
			var a:Array = new Array();
			for (var i:Number = 0; i < mcwQeue.length; i++) {
				var iMcw:LcMcWrapper = mcwQeue[i];
				if (mcw != iMcw)
					a.push(iMcw);
			}
			mcwQeue = a;
		}
	}
	
	
	// Listeners
	
	private function mcStateChangeListener(eventObject:Object):Void {
		
		// Show the new page.
		if (eventObject.state == LcMcWrapper.STATE_OFF) {
			eventObject.target.removeEventListener(EventConstants.MC_STATE_CHANGE, mcStateChangeDelegate);
			mcwQeue.shift();
			var next:LcMcWrapper = mcwQeue[0];
			if (mcwQeue.length == 1) {
				next.state = LcMcWrapper.STATE_IN;
				currentMcw = next;
			} else {
				next.state = LcMcWrapper.STATE_OUT;
			}
		}
		
	}
	
	
}